package com.example.backend.controller.admin;

import com.example.backend.common.api.R;
import com.example.backend.common.tree.MenuTree;
import com.example.backend.entity.Permission;
import com.example.backend.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单管理控制器
 */
@RestController
@RequestMapping("/admin/menu")
@RequiredArgsConstructor
public class MenuController {

    private final PermissionService permissionService;

    /**
     * 获取菜单树
     */
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<MenuTree>> getMenuTree() {
        return R.ok(permissionService.getAllMenuTree());
    }

    /**
     * 创建菜单
     */
    @PostMapping
    @PreAuthorize("hasAuthority('system:menu:add')")
    public R<Void> create(@RequestBody Permission permission) {
        return permissionService.save(permission) ? R.ok() : R.fail("创建失败");
    }

    /**
     * 更新菜单
     */
    @PutMapping
    @PreAuthorize("hasAuthority('system:menu:edit')")
    public R<Void> update(@RequestBody Permission permission) {
        return permissionService.updateById(permission) ? R.ok() : R.fail("更新失败");
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public R<Void> delete(@PathVariable Long id) {
        return permissionService.removeById(id) ? R.ok() : R.fail("删除失败");
    }
} 